package com.ucode.dcse.handler.crm;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.otter.canal.protocol.CanalEntry;
import com.ucode.dcse.TableCanalData;
import com.ucode.dcse.handler.TableDataHandler;
import com.ucode.search.crm.model.ESCustomer;
import com.ucode.springboot.starter.ESsearch.repository.ElasticsearchDocSourceTemplate;
import com.ucode.springboot.starter.ESsearch.repository.ElasticsearchSearchTemplate;
import com.ucode.tool.util.ListPageModel;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;

@Component("ucode_crm.crm_follow_team_user")
public class FollowTeamUserDataHandler implements TableDataHandler {
    /**
     * 如果映射Map为空,或者表字段找不到映射，则以数据库为准
     */
    @SuppressWarnings("serial")
    private Map<String, String> crm_follow_team_user_mapping = new HashMap<String, String>() {
        {
            put("id", "id");
            put("targetId", "targetId");
            put("targetType", "targetType");
            put("userId", "userId");
            put("power", "power");
        }
    };

    @Autowired
    private ElasticsearchDocSourceTemplate<ESCustomer, Long> esCustomerDocSourceTemplate;

    @Autowired
    private ElasticsearchSearchTemplate<ESCustomer, Long> esCustomerSearchTemplate;

    @Override
    public void handle(TableCanalData tableCanalData) {

        try {
            JSONArray list = null;
            if (CanalEntry.EventType.INSERT.equals(tableCanalData.getEventType())
                    || CanalEntry.EventType.UPDATE.equals(tableCanalData.getEventType())) {
                list = tableCanalData.getAfterDatas();
            } else if (CanalEntry.EventType.DELETE.equals(tableCanalData.getEventType())) {
                list = tableCanalData.getBeforeDatas();
            }

            if (list != null && list.size() > 0) {
                Map<String, Map<Long, Set<String>>> map = new HashMap<String, Map<Long, Set<String>>>();
                for (int i = 0; i < list.size(); i++) {
                    JSONObject obj = list.getJSONObject(i);
                    String targetType = obj.getString("targetType");
                    String targetId = obj.getString("targetId");
                    String power = obj.getString("power");
                    String userId = obj.getString("userId");
                    if (StrUtil.isNotBlank(targetType)) {
                        Map<Long, Set<String>> tagMap = map.get(targetType);
                        Set<String> userIds = null;
                        if (tagMap == null) {
                            tagMap = new HashMap<>();
                            userIds = new HashSet<String>();
                        } else {
                            userIds = tagMap.get(targetId);
                            if (userIds == null)
                                userIds = new HashSet<String>();
                        }

                        // 权限类型:1、负责人权限(读写)2、读写权限3、只读权限
                        if (!"1".equals(power)) {
                            userIds.add(userId);
                            tagMap.put(Long.valueOf(targetId), userIds);
                            map.put(targetType, tagMap);
                        }

                    }
                }

                Iterator<Entry<String, Map<Long, Set<String>>>> iterator = map.entrySet().iterator();
                while (iterator.hasNext()) {
                    String key = iterator.next().getKey();
                    Map<Long, Set<String>> value = iterator.next().getValue();

                    /**
                     * 更新客户、商机、合同跟进团队策略： 1、拦截跟进团队成员数据表数据添加、更新、删除数据
                     * 2、查询ES库中相关的团队成员数据 3、通过并集、差集完成团队成员数据更新
                     */
                    if ("0".equals(key) && MapUtil.isNotEmpty(value)) {

                        // 更新客户跟进团队
                        Set<Long> keys = value.keySet();
                        Long[] ids = keys.toArray(new Long[keys.size()]);
                        List<ESCustomer> esCustomers = esCustomerSearchTemplate.getByIds(ids, ESCustomer.class);
                        Map<Long, ESCustomer> esObjMap = new HashMap<Long, ESCustomer>();
                        if (CollUtil.isNotEmpty(esCustomers)) {
                            for (ESCustomer esCustomer : esCustomers) {
                                esObjMap.put(esCustomer.getId(), esCustomer);
                            }
                        }

                        Iterator<Entry<Long, Set<String>>> it = value.entrySet().iterator();
                        List<ESCustomer> updataObjs = new ArrayList<ESCustomer>();
                        while (it.hasNext()) {
                            Long itkey = it.next().getKey();
                            Set<String> teamUserIds = it.next().getValue();
                            if (CollUtil.isNotEmpty(teamUserIds)) {
                                ESCustomer esobj = esObjMap.get(itkey);
                                if (esobj != null && StrUtil.isNotBlank(esobj.getTeamUserIds())) {
                                    String[] datas = esobj.getTeamUserIds().split(" ");

                                    if (CanalEntry.EventType.DELETE.equals(tableCanalData.getEventType())) {
                                        teamUserIds.removeAll(Arrays.asList(datas));
                                    } else {
                                        teamUserIds.addAll(Arrays.asList(datas));
                                    }
                                }
                                String userIdsStr = StrUtil.join(" ", teamUserIds);

                                esobj = new ESCustomer();
                                esobj.setId(itkey);
                                esobj.setTeamUserIds(userIdsStr);
                                updataObjs.add(esobj);
                            }
                        }

                        if (updataObjs.size() > 0) {
                            ListPageModel listPageModel = new ListPageModel(updataObjs, 200);
                            for (int page = 1; page <= listPageModel.getTotalPages(); page++) {
                                List<ESCustomer> pagDatas = listPageModel.getObjects(page);
                                esCustomerDocSourceTemplate.update(pagDatas);
                            }
                        }

                    }else if ("2".equals(key) && MapUtil.isNotEmpty(value)) {
                        // 更新商机跟进团队
                        
                    }else if ("3".equals(key) && MapUtil.isNotEmpty(value)) {
                        // 更新合同跟进团队
                        
                    }

                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public Map<String, String> getMapping() {
        return crm_follow_team_user_mapping;
    }

}
